/**
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: UMP Technology Co. Ltd</p>
 * <p>2014年6月9日</p>
 * @author Zhang Wensheng
 */
package com.jflm.util;

import java.security.MessageDigest;

/**
 * desc: MD5工具类
 * @author Zhang Wensheng
 * date:2014年6月9日
 */
public class MD5Util {
	
	private static final String bcd_table = "0123456789ABCDEF";

	private static String digest(byte[] bin, int off, int len) {
		if (off > bin.length){
			return null;
		}
		len = Math.min(len, bin.length - off);
		char[] cbuf = new char[len * 2];
		for (int i = off; i < off + len; ++i) {
			int x = (i - off) * 2;
			cbuf[x] = bcd_table.charAt(bin[i] >>> 4 & 0xF);
			cbuf[(x + 1)] = bcd_table.charAt(bin[i] & 0xF);
		}
		return new String(cbuf);
	}
	
	private static byte[] bcd_table(byte[] msgBytes, int offset, int len, String alg)
			throws Exception {
		MessageDigest aMessageDigest = null;
		byte[] result = null;
		aMessageDigest = MessageDigest.getInstance(alg);
		if (aMessageDigest != null) {
			aMessageDigest.reset();
			aMessageDigest.update(msgBytes, offset, len);
			result = aMessageDigest.digest();
		}
		return result;
	}
	
	public static String digest(String src) throws Exception{
		byte[] bytes = bcd_table(src.getBytes() ,0 ,src.getBytes().length,"MD5");
		return digest(bytes, 0, bytes.length);
	}
	
}
